<template>
  <div class="min-h-screen bg-gray-100 flex items-center justify-center py-12 px-4 sm:px-6 lg:px-8">
    <div class="max-w-md w-full space-y-8 bg-white p-8 rounded-lg shadow-md">
      <div>
        <h2 class="mt-6 text-center text-3xl font-extrabold text-gray-900">注册账号</h2>
        <p class="mt-2 text-center text-sm text-gray-600">
          已有账号？
          <router-link to="/login" class="text-primary hover:text-primary-dark">
            立即登录
          </router-link>
        </p>
      </div>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        class="mt-8 space-y-6"
      >
        <el-form-item prop="nickname">
          <el-input
            v-model="form.nickname"
            placeholder="用户名"
            :prefix-icon="User"
          />
        </el-form-item>

        <el-form-item prop="phone">
          <el-input
            v-model="form.phone"
            placeholder="手机号"
            :prefix-icon="Phone"
          />
        </el-form-item>

        <el-form-item prop="password">
          <el-input
            v-model="form.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

        <el-form-item prop="confirmPassword">
          <el-input
            v-model="form.confirmPassword"
            type="password"
            placeholder="确认密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>

<!--        <el-form-item prop="code" class="flex-1">-->
<!--          <div class="flex gap-4">-->
<!--            <el-input-->
<!--              v-model="form.code"-->
<!--              placeholder="验证码"-->
<!--              :prefix-icon="Message"-->
<!--            />-->
<!--            <el-button-->
<!--                type="primary"-->
<!--                :disabled="countdown > 0"-->
<!--                class="w-32 !flex-shrink-0"-->
<!--              @click="sendCode"-->
<!--            >-->
<!--              {{ countdown > 0 ? `${countdown}s后重新发送` : '获取验证码' }}-->
<!--            </el-button>-->
<!--          </div>-->
<!--        </el-form-item>-->

        <div class="flex items-center">
          <el-checkbox v-model="form.agreement" class="flex-1">
            我已阅读并同意
            <a href="#" class="text-primary hover:text-primary-dark">《用户协议》</a>
            和
            <a href="#" class="text-primary hover:text-primary-dark">《隐私政策》</a>
          </el-checkbox>
        </div>

        <div>
          <el-button
            type="primary"
            class="w-full"
            :loading="loading"
            @click="handleRegister"
          >
            注册
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Phone, Message } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import {register} from "@/api/user.js";

const router = useRouter()
const userStore = useUserStore()
const formRef = ref(null)
const loading = ref(false)
const countdown = ref(0)

const form = ref({
  nickname: '',
  phone: '',
  password: '',
  confirmPassword: '',
  code: '',
  agreement: false
})

const validatePass = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请输入密码'))
  } else {
    if (form.value.confirmPassword !== '') {
      formRef.value?.validateField('confirmPassword')
    }
    callback()
  }
}

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== form.value.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  nickname: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  password: [
    { required: true, validator: validatePass, trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, validator: validatePass2, trigger: 'blur' }
  ],
  // code: [
  //   { required: true, message: '请输入验证码', trigger: 'blur' },
  //   { len: 6, message: '验证码长度应为6位', trigger: 'blur' }
  // ]
}

const startCountdown = () => {
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
    }
  }, 1000)
}

const sendCode = async () => {
  try {
    await formRef.value?.validateField('phone')
    // TODO: 调用发送验证码接口
    ElMessage.success('验证码已发送')
    startCountdown()
  } catch (error) {
    // 验证失败
  }
}

const handleRegister = async () => {
  if (!formRef.value) return

  await formRef.value.validate(async (valid, fields) => {
    if (valid) {
      if (!form.value.agreement) {
        ElMessage.warning('请阅读并同意用户协议和隐私政策')
        return
      }

      loading.value = true
      try {
        await register(form.value)
        ElMessage.success('注册成功')
        await router.push('/login')
      } catch (error) {
        ElMessage.error(error.message || '注册失败')
      } finally {
        loading.value = false
      }
    }
  })
}
</script>
